package com.woniuxy.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.conmon.MyPageData;
import com.woniuxy.mapper.DoctorMapper;
import com.woniuxy.mapper.DoctorScheduleMapper;
import com.woniuxy.mapper.HospitalMapper;
import com.woniuxy.mapper.MedicalPackageMapper;
import com.woniuxy.pojo.*;
import com.woniuxy.pojo.dto.DoctorScheduleDTO;
import com.woniuxy.pojo.dto.SearchMedicalDTO;
import com.woniuxy.pojo.vo.AppointmentVO;
import com.woniuxy.pojo.vo.DoctorScheduleVO;
import com.woniuxy.service.DoctorScheduleService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("doctorSchedule")
@Api(tags = "医生排班接口")

public class DoctorScheduleController {
    @Autowired
    private DoctorScheduleService doctorScheduleService;
    @Autowired
    private DoctorScheduleMapper doctorScheduleMapper;
    @Autowired
    private DoctorMapper doctorMapper;
    @Autowired
    private HospitalMapper hospitalMapper;
    @Autowired
    private MedicalPackageMapper medicalPackageMapper;

    @GetMapping("/getDoctorSchedule")
    @ApiOperation(value = "查询所有医生排班信息")
    public Result getDoctorSchedule() {
        List<DoctorSchedule> doctorSchedules = doctorScheduleService.list();
        return Result.ok(doctorSchedules);
    }

    @PostMapping("/batchDeleteSchedule")
    @ApiOperation(value = "批量删除医生排班信息")
    public Result batchDeleteSchedule(@RequestBody List<Integer> ids) {
        boolean b = doctorScheduleService.removeByIds(ids);
        return b ? Result.ok() : Result.fail();
    }

    @GetMapping("/getAppointmentData/{id}")
    @ApiOperation(value = "根据id查询医生排班信息")
    public Result getAppointmentData(@PathVariable("id") Integer id) {
        DoctorSchedule doctorSchedule = doctorScheduleService.getById(id);
        return Result.ok(doctorSchedule);
    }

    // 新增预约
    @PostMapping("/create")
    @ApiOperation(value = "新增预约")
    public Result create(@RequestBody DoctorSchedule schedule) {
        // 业务验证
        if (schedule.getAppointmentType() == null) {
            return Result.fail("业务类型不能为空");
        }
        if (schedule.getStartTime() == null || schedule.getEndTime() == null) {
            return Result.fail("时间段不能为空");
        }

        // 设置默认值
        if (schedule.getRegisteredCount() == null) {
            schedule.setRegisteredCount(0);
        }
        if (schedule.getStatus() == null) {
            schedule.setStatus(1); // 默认启用
        }

        schedule.setCreateTime(new Date());
        schedule.setUpdateTime(new Date());

        boolean success = doctorScheduleService.save(schedule);
        return success ? Result.ok("新增成功") : Result.fail("新增失败");
    }

    // 修改预约
    @PutMapping("/update/{id}")
    @ApiOperation(value = "修改预约")
    public Result update(@PathVariable Integer id, @RequestBody DoctorSchedule schedule) {
        // 验证ID是否存在
        DoctorSchedule existing = doctorScheduleService.getById(id);
        if (existing == null) {
            return Result.fail("记录不存在");
        }

        // 更新字段
        existing.setAppointmentType(schedule.getAppointmentType());
        existing.setAppointmentType(schedule.getAppointmentType());
        existing.setStartTime(schedule.getStartTime());
        existing.setEndTime(schedule.getEndTime());
        existing.setUpdateTime(new Date());

        boolean success = doctorScheduleService.updateById(existing);
        return success ? Result.ok("修改成功") : Result.fail("修改失败");
    }

    @GetMapping("/getRegistrationData/{pageNum}/{pageSize}")
    @ApiOperation(value = "查询所有预约信息")
    public Result getRegistrationData(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
        MyPageData doctorSchedules = doctorScheduleService.getRegistrationData(pageNum, pageSize);
        return Result.ok(doctorSchedules);
    }

    @GetMapping("/getDoctorDetail/{pageNum}/{pageSize}")
    @ApiOperation(value = "查询医生详情")
    public Result getDoctorDetail(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
        MyPageData doctorSchedules = doctorScheduleService.getDoctorDetail(pageNum, pageSize);
        return Result.ok(doctorSchedules);
    }

    @GetMapping("/getDoctorName")
    @ApiOperation(value = "查询所有医生名称")
    public Result getDoctorName() {
        QueryWrapper<Doctor> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name");
        List<Doctor> doctornames = doctorMapper.selectList(wrapper);
        return Result.ok(doctornames);
    }

    @GetMapping("/getHospitalNames")
    @ApiOperation(value = "查询所有医院名称")
    public Result getHospitalNames() {
        QueryWrapper<Hospital> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name");
        List<Hospital> hospitals = hospitalMapper.selectList(wrapper);
        return Result.ok(hospitals);
    }

    @GetMapping("/getPackageNames")
    @ApiOperation(value = "查询所有套餐名称")
    public Result getPackageNames() {
        QueryWrapper<MedicalPackage> wrapper = new QueryWrapper<>();
        wrapper.select("id", "package_name");
        List<MedicalPackage> packages = medicalPackageMapper.selectList(wrapper);
        return Result.ok(packages);
    }

    @GetMapping("/getMaxPatientsOptions")
    @ApiOperation(value = "获取人数上限选项列表")
    public Result getMaxPatientsOptions() {
        QueryWrapper<DoctorSchedule> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT max_patients");
        List<DoctorSchedule> list = doctorScheduleMapper.selectList(wrapper);

        // 提取数值
        List<Integer> result = list.stream()
                .map(DoctorSchedule::getMaxPatients)
                .collect(Collectors.toList());

        return Result.ok(result);
    }

    @PostMapping("/searchQueryFrom/{pageNum}/{pageSize}")
    @ApiOperation(value = "条件查询信息")
    public Result searchQueryFrom(@RequestBody DoctorScheduleDTO queryDTO, @PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
        Page<DoctorScheduleVO> page = doctorScheduleService.searchQuery(queryDTO, pageNum, pageSize);
        return Result.ok(page);
    }

    @GetMapping("/getAppointmentDetail/{id}")
    @ApiOperation(value = "查询医生的信息详情")
    public Result getAppointmentDetail(@PathVariable("id") Integer id) {
        AppointmentVO doctorSchedule = doctorScheduleService.getAppointmentDetail(id);
        return Result.ok(doctorSchedule);
    }

    @GetMapping("/download")
    @ApiOperation(value = "导出详情的Excel表")
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("医生详情列表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        MyPageData doctorDetail = doctorScheduleService.getDoctorDetail(1, 9);
        List<DoctorSchedule> dataList = doctorDetail.getData();
        ServletOutputStream outputStream = response.getOutputStream();
        EasyExcel.write(response.getOutputStream(), DoctorSchedule.class).sheet("医生").doWrite(dataList);
        outputStream.flush();
        outputStream.close();
    }

    @GetMapping("/getMedicalData/{pageNum}/{pageSize}")
    @ApiOperation(value = "查询所有体检信息")
    public Result getMedicalData(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") int pageSize) {
        MyPageData doctorSchedules = doctorScheduleService.getMedicalData(pageNum, pageSize);
        return Result.ok(doctorSchedules);

    }

    @PostMapping("/searchDoctorSchedule/{pageNum}/{pageSize}")
    @ApiOperation(value = "条件查询患者体检信息")
    public Result searchDoctorSchedule(@RequestBody SearchMedicalDTO query, @PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
        Page<DoctorScheduleVO> page = doctorScheduleService.searchDoctorSchedule(query, pageNum, pageSize);
        return Result.ok(page);
    }

}
